var _excluded = ["authed", "initDeptDeep", "options", "value", "onChange", "popupClassName", "searchNameService", "findChildService", "treeService", "authedTreeService", "nodeDetailService"];
function _extends() { _extends = Object.assign ? Object.assign.bind() : function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import React, { useCallback, useEffect, useState } from "react";
import { TreeSelect } from "antd";
import { debounce } from "@szzj/utils";
import useDeptTree from "./hooks";
import "antd/es/tree-select/style/index.js";
import "./index.less";
/**
 * 部门选择
 * @param param0
 * @returns
 */
export default function DeptTreeSelectCustom(_ref) {
  var authed = _ref.authed,
    initDeptDeep = _ref.initDeptDeep,
    options = _ref.options,
    value = _ref.value,
    onChange = _ref.onChange,
    popupClassName = _ref.popupClassName,
    searchNameService = _ref.searchNameService,
    findChildService = _ref.findChildService,
    treeService = _ref.treeService,
    authedTreeService = _ref.authedTreeService,
    nodeDetailService = _ref.nodeDetailService,
    rest = _objectWithoutProperties(_ref, _excluded);
  var _useState = useState(undefined),
    _useState2 = _slicedToArray(_useState, 2),
    innerValue = _useState2[0],
    setInnerValue = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    expandedKeys = _useState4[0],
    setExpandedKeys = _useState4[1];
  var _useDeptTree = useDeptTree({
      authed: authed,
      initDeptDeep: initDeptDeep,
      searchNameService: searchNameService,
      findChildService: findChildService,
      treeService: treeService,
      authedTreeService: authedTreeService,
      nodeDetailService: nodeDetailService
    }),
    fetchInitialTree = _useDeptTree.fetchInitialTree,
    treeNodes = _useDeptTree.treeNodes,
    findNode = _useDeptTree.findNode,
    findAncestorNodes = _useDeptTree.findAncestorNodes,
    loading = _useDeptTree.loading,
    detailLoading = _useDeptTree.detailLoading,
    loadData = _useDeptTree.loadData,
    fetchDeptNodeDetail = _useDeptTree.fetchDeptNodeDetail,
    treeNodesBySearch = _useDeptTree.treeNodesBySearch,
    searchTreeNodesByName = _useDeptTree.searchTreeNodesByName,
    searchExpandedKeys = _useDeptTree.searchExpandedKeys,
    clearTreeNodesBySearch = _useDeptTree.clearTreeNodesBySearch;

  /**
   * 如果外部传入 treeNodes，优先级高于内部 treeNodes
   */
  useEffect(function () {
    if (!(options !== null && options !== void 0 && options.length) && !treeNodes.length) fetchInitialTree();
  }, [options]);

  /**
   * 编辑态回显节点名称时用，当节点不在初始化树中
   */
  useEffect(function () {
    if (value && value !== innerValue) {
      /**
       * 找不到节点时，请求详情数据
       */
      if (!findNode(value)) {
        /**
         * 获取节点详情数据，继而通过 useEffect 塞满该详情节点路径下的子节点
         */
        fetchDeptNodeDetail(value);
        setInnerValue(value);
      } else {
        setInnerValue(value);
      }
    }
  }, [value, fetchDeptNodeDetail]);

  /**
   * 默认展开一级节点
   */
  useEffect(function () {
    if (treeNodes.length) {
      setExpandedKeys(treeNodes.map(function (node) {
        return node.key;
      }));
    }
  }, [treeNodes.length]);

  /**
   * 值变更时，树节点展开节点包含所选节点路径
   */
  useEffect(function () {
    if (innerValue) {
      var ancestorNodes = findAncestorNodes(innerValue);
      var keysToFill = ancestorNodes.filter(function (node) {
        return !node.isLeaf && !expandedKeys.some(function (key) {
          return node.key === key;
        });
      }).map(function (node) {
        return node.key;
      });
      setExpandedKeys([].concat(_toConsumableArray(expandedKeys), _toConsumableArray(keysToFill)));
    }
  }, [innerValue, findAncestorNodes]);
  var handleChange = useCallback(function (val, labelList, extra) {
    setInnerValue(val);
    // @ts-ignore
    onChange === null || onChange === void 0 ? void 0 : onChange(val, labelList, extra);
    clearTreeNodesBySearch();

    /**
     * 当节点在树中，通过获取节点详情塞满该详情节点路径下的子节点
     */
    if (val && !findNode(val)) {
      fetchDeptNodeDetail(val);
    }
  }, [onChange, clearTreeNodesBySearch, findNode, fetchDeptNodeDetail, expandedKeys, findAncestorNodes, setExpandedKeys]);
  var handleSearch = useCallback(function (searchValue) {
    if (searchValue && searchValue.length >= 2) {
      searchTreeNodesByName(searchValue);
    } else if (!searchValue) {
      clearTreeNodesBySearch();
    }
  }, [searchTreeNodesByName]);
  return /*#__PURE__*/React.createElement(TreeSelect, _extends({
    placeholder: "\u8BF7\u9009\u62E9\u90E8\u95E8",
    showCheckedStrategy: TreeSelect.SHOW_ALL
  }, rest, {
    popupClassName: popupClassName ? "drs-dept-tree-select-popup ".concat(popupClassName) : "drs-dept-tree-select-popup",
    loading: loading || detailLoading
    // @ts-ignore
    ,
    loadData: loadData,
    treeData: treeNodesBySearch.length ? treeNodesBySearch : options !== null && options !== void 0 ? options : treeNodes,
    treeDefaultExpandedKeys: treeNodesBySearch.length ? treeNodesBySearch.map(function (node) {
      return node.key;
    }) : (options !== null && options !== void 0 ? options : treeNodes).map(function (node) {
      return node.key;
    })
    /**
     * treeExpandedKeys, onTreeExpand：搜索状态，节点展开情况不受控
     * 2023.11.03 - 搜索状态也受控处理，解决最后一层节点不展开的问题
     */,
    treeExpandedKeys: treeNodesBySearch.length ? searchExpandedKeys : expandedKeys,
    onTreeExpand: treeNodesBySearch.length ? undefined : function (keys) {
      return setExpandedKeys(keys);
    },
    fieldNames: {
      value: "key",
      label: "title",
      children: "children"
    },
    showSearch: true,
    filterTreeNode: function filterTreeNode() {
      return true;
    },
    onSearch: debounce(handleSearch, 1000),
    onBlur: function onBlur() {
      return clearTreeNodesBySearch();
    },
    value: innerValue,
    onChange: handleChange
  }));
}